package org.sanguine.study.hometasks.second;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

import org.sanguine.study.hometasks.first.TaskWorker;
import org.sanguine.study.hometasks.second.auxiliary.Word;

public class Task10 implements TaskWorker {
	private String fileName;
	private File file;
	private Map<Word, Integer> text = new HashMap<>();
	private PrintWriter out;

	public static void main(String[] args) {
		TaskWorker task = new Task10();
		
		if (task.setUp(null, null, args)) {
			task.doTask();
		} else {
			System.err.println("Setup failed");
		}
	}

	private void printUsage() {
		System.err.println("USAGE: java -jar Task10.jar 'fileName'");
	}

	@Override
	public boolean setUp(Reader in, PrintWriter out, String[] args) {
		if (args == null || args.length < 1) {
			printUsage();
			return false;
		}
		fileName = args[0];
		file = new File(fileName);
		this.out = out;
		
		if (file.isFile()) return true;
		
		System.err.printf("File %s is not file or does not exist%n", fileName);
		file = null;
		return false;
	}

	@Override
	public void doTask() {
		if (file == null || out == null) return;

		readAndCountWords();
		printResult();
	}

	private void readAndCountWords() {
		try (Reader in = new FileReader(file)) {
			Scanner scanner = new Scanner(in);
			scanner.useDelimiter("[\\s\\,\\.\\(\\)\\{\\}\\[\\]\"]+");
			while (scanner.hasNext()) {
				Word word;
				try {
					word = new Word(scanner.next(), true);
				} catch (IllegalArgumentException e) {
					continue;
				}
				Integer count = text.get(word);
				if (count == null) text.put(word, new Integer(1));
				else text.put(word, new Integer(count + 1));
			}
			scanner.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void printResult() {
		for (Word s : text.keySet()) out.printf("%s %d%n", s, text.get(s));
	}

}
